package JUC;

import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author 豆包LU
 * @date 2023/5/8 14:19
 */
public class LinkedBlockingDequeExample {
    public static void main(String[] args) {
        // 创建 LinkedBlockingDeque 队列，指定容量大小
        LinkedBlockingDeque<Integer> deque = new LinkedBlockingDeque<>(5);

        // 生产者线程向队列中添加元素
        Thread producer = new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    // 添加元素到队列尾部，如果队列已满，则会阻塞等待
                    deque.put(i);
                    System.out.println("生产者线程添加元素：" + i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 消费者线程从队列中获取元素
        Thread consumer = new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    Thread.sleep(1000);
                    // 获取队列头部元素，如果队列为空，则会阻塞等待
                    int value = deque.take();
                    System.out.println("消费者线程获取元素：" + value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        producer.start();
        consumer.start();
    }
}
